/**
 * 千分位格式化
 * @param number 数值(非空)
 * @param decimalPlaces 小数位(可空)
 * @param thousandsSeparator 千分位分隔符(可空)
 * @param decimalSeparator 小数符，默认"."(可空)
 * @param prefix 前缀(可空)
 * @param suffix 后缀(可空)
 * @returns {String}
 */
export const numberFormat = (
    number,
    decimalPlaces = 2,
    thousandsSeparator = ',',
    decimalSeparator = '.',
    prefix = '',
    suffix = ''
) => {
    const isNumber = obj => {
        const type = typeof (obj)
        // eslint-disable-next-line no-restricted-globals
        return (type === 'number' || type === 'string') && !isNaN(obj - parseFloat(obj))
    }

    if (isNumber(number)) {
        const bNegative = number < 0
        let sOutput = String(number)
        const sDecimalSeparator = decimalSeparator || '.'
        let nDotIndex
        if (isNumber(decimalPlaces)) {
            // Round to the correct decimal place
            const nDecimalPlaces = decimalPlaces
            // eslint-disable-next-line no-restricted-properties
            const nDecimal = Math.pow(10, nDecimalPlaces)
            sOutput = String(Math.round(number * nDecimal) / nDecimal)
            nDotIndex = sOutput.lastIndexOf('.')
            if (nDecimalPlaces > 0) {
                // Add the decimal separator
                if (nDotIndex < 0) {
                    sOutput += sDecimalSeparator
                    nDotIndex = sOutput.length - 1
                // eslint-disable-next-line brace-style
                }
                // Replace the "."
                else if (sDecimalSeparator !== '.') {
                    sOutput = sOutput.replace('.', sDecimalSeparator)
                }
                // Add missing zeros
                while (sOutput.length - 1 - nDotIndex < nDecimalPlaces) {
                    sOutput += '0'
                }
            }
        }
        if (thousandsSeparator) {
            const sThousandsSeparator = thousandsSeparator
            nDotIndex = sOutput.lastIndexOf(sDecimalSeparator)
            nDotIndex = nDotIndex > -1 ? nDotIndex : sOutput.length
            let sNewOutput = sOutput.substring(nDotIndex)
            let nCount = -1;
            let i
            // eslint-disable-next-line no-plusplus
            for (i = nDotIndex; i > 0; i--) {
                // eslint-disable-next-line no-plusplus
                nCount++
                if (nCount % 3 === 0 && i !== nDotIndex && (!bNegative || i > 1)) {
                    sNewOutput = sThousandsSeparator + sNewOutput
                }
                sNewOutput = sOutput.charAt(i - 1) + sNewOutput
            }
            sOutput = sNewOutput
        }
        // Prepend prefix
        sOutput = prefix ? prefix + sOutput : sOutput
        // Append suffix
        sOutput = suffix ? sOutput + suffix : sOutput
        return sOutput
    }
    return number
};
